# this file shows mongrel with a pooled db
#  ab -n 10 -c 10 http://127.0.0.1:3000/
#
# note: requires patched evented_mongrel [currently] [fibered mongrel]
require 'rubygems'
require 'swiftcore/evented_mongrel'
require 'fibered_mongrel'
require '../../source/asymy/asymy' # my version has an added exec_and_fiber_yield and an added em_connection to this class, which are necessary
require '../setup_db_opts'
require 'connection_pool_fibered'

 class SimpleHandler < Mongrel::HttpHandler
    @@count_ever = 0
    
    def process(request, response)
      # note that @'s here are shared among mongrel's incoming connections!--don't use them
      unless defined? @@pool
        @@pool = ConnectionPool.new 10, $opts # have to initialize it a little late in the game, so that EM is already fired up
      else

      end
      my_count = @@count_ever
      @@count_ever += 1
      response.start(200) do |head,out|
        head["Content-Type"] = "text/plain"
        out.write("hello!\n")

        # conn = Asymy::Connection.new $opts # TODO why would it err with this in there, though? huh?
      	1.times { |n|
      	   local_var = nil # an example of how to set local vars :)
      	   size = [:small, :big][my_count % 2]
      	   query = "select count(*) from #{ size == :small ? 'users' : 'user_sessions' }"
      	   print "starting #{my_count} #{size} #{n}\n"
           @@pool.exec_when_available(query) {|h, c| local_var = [h,c]}
           print "done #{my_count} #{size} #{n}\n"
      	}
      end
    end
 end

 h = Mongrel::HttpServer.new("0.0.0.0", 3000)
 h.register("/", SimpleHandler.new)
 h.register("/files", Mongrel::DirHandler.new("."))
 h.run.join
